package com.android.view.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.model.entity.res.SendCodeResult;
import com.android.presenter.info.SendCodePresenter;
import com.android.presenter.info.VerifyCodePresenter;
import com.android.presenter.iview.IRegisterView;
import com.android.presenter.iview.IVerifySmsView;
import com.android.util.HideInputUtil;
import com.android.util.ToastUtil;
import com.android.util.country.Country;
import com.android.R;
import com.android.model.entity.res.VerifyCodeResult;
import com.android.presenter.iview.ISendCodeView;
import com.android.presenter.info.RegisterPresenter;
import com.android.util.SimplePrompt;
import com.android.util.country.CountryPicker;
import com.android.util.country.OnPick;
import com.android.view.activity.base.Constants;
import com.android.view.activity.base.ToolbarBaseActivity;

import butterknife.BindView;
import retrofit2.Response;

/**
 * 注册页面
 * Created by TenFace on 2018/4/19.
 */

public class RegisterActivity extends ToolbarBaseActivity implements IRegisterView, IVerifySmsView, ISendCodeView {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    @BindView(R.id.ivDelete)
    ImageView ivDelete;
    @BindView(R.id.ivSwitchCountry)
    ImageView ivSwitchCountry;
    @BindView(R.id.ivFlag)
    ImageView ivFlag;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etSMS)
    EditText etSMS;
    @BindView(R.id.etPWD)
    EditText etPWD;
    @BindView(R.id.etReferral)
    EditText etReferral;
    @BindView(R.id.tvSend)
    TextView tvSend;
    @BindView(R.id.tvTerms)
    TextView tvTerms;
    @BindView(R.id.tvCountry)
    TextView tvCountry;
    @BindView(R.id.tvToLogin)
    TextView tvToLogin;
    @BindView(R.id.btnRegister)
    Button btnRegister;
    @BindView(R.id.hideShowPassword)
    CheckBox hideShowPassword;
    @BindView(R.id.cbUseTerms)
    CheckBox cbUseTerms;
    private RegisterPresenter registerPresenter;
    private SendCodePresenter sendCodePresenter;
    private VerifyCodePresenter verifyCodePresenter;
    private String accountPhone;
    private String phoneCode;
    private String accountPWD;
    private String accountInviteCode;

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_register);
    }

    @Override
    protected void initView() {
        int color = getResourceColor(R.color.white);
        setStatusBarColor(color, 0);
        setStatusBarMode(true);
    }

    @Override
    protected void obtainData() {
        registerPresenter = new RegisterPresenter(this);
        sendCodePresenter = new SendCodePresenter(this);
        verifyCodePresenter = new VerifyCodePresenter(this);
    }

    @Override
    protected void initEvent() {
        ivSwitchCountry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CountryPicker.newInstance(null, new OnPick() {
                    @Override
                    public void onPick(Country country) {
                        if (country.flag != 0) ivFlag.setBackgroundResource(country.flag);
                        tvCountry.setText("+" + country.code);
                    }
                }).show(getSupportFragmentManager(), "country");
            }
        });
        hideShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPWD.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPWD.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPhone.setText("");
            }
        });
        tvToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                restartTimer(tvSend);
                sendCodePresenter.sendSmsCode("", etPhone.getText().toString(), "PHONE", "REGISTER");
            }
        });
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                accountPhone = etPhone.getText().toString();
                phoneCode = etSMS.getText().toString();
                accountPWD = etPWD.getText().toString();
                accountInviteCode = etReferral.getText().toString();
                if (accountPhone.length() < 1) {
                    ToastUtil.show("请输入手机号码！");
                } else {
                    if (phoneCode.length() < 6) {
                        ToastUtil.show("请输入正确的验证码！");
                    } else {
                        if (etPWD.getText().length() < 8) {
                            ToastUtil.show("请输入正确的密码！");
                        } else {
                            if (!cbUseTerms.isChecked()) {
                                ToastUtil.show("请勾选用户协议！");
                            } else {
                                btnRegister.setClickable(false);
                                SimplePrompt.getIntance().showLoadingMessage(RegisterActivity.this, "请求注册中...", false);
                                verifyCodePresenter.verifySmsCode("", accountPhone, phoneCode, "PHONE", "REGISTER");
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Constants.activityList.put(TAG, this);
    }

    @Override
    public void sendCodeSuccess(SendCodeResult sendCodeResult) {
        if (sendCodeResult != null) {
            ToastUtil.show(sendCodeResult.getMessage());
            Log.e("registerSuccess", "请求成功>>>>>>>" + sendCodeResult.getExpiredTime());
        }
    }

    @Override
    public void sendCodeFail(int status, String desc) {
        ToastUtil.show(desc + "，验证码发送失败！");
    }


    @Override
    public void verifySmsSuccess(VerifyCodeResult verifyCodeResult) {
//        SimplePrompt.getIntance().dismiss();
        if (verifyCodeResult != null) {
            registerPresenter.getRegisterStatus("REGISTER", accountPhone, accountPWD, accountInviteCode, verifyCodeResult.getToken());
        }
    }

    @Override
    public void verifySmsFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
        ToastUtil.show(desc + "，校验失败！");
    }

    @Override
    public void registerSuccess(Response<Void> voidResponse) {

        if (voidResponse.code() == 200) {
            ToastUtil.show("注册成功！");
        }

        btnRegister.setClickable(true);
        SimplePrompt.getIntance().dismiss();
    }

    @Override
    public void registerFail(int status, String desc) {
        btnRegister.setClickable(true);
        SimplePrompt.getIntance().dismiss();
        ToastUtil.show(desc + "，注册失败！");
        Log.e("registerSuccess", "请求失败");
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (HideInputUtil.isShouldHideInput(v, ev)) {
                if (HideInputUtil.hideInputMethod(this, v)) {
//                    return true; //隐藏键盘时，其他控件不响应点击事件,注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void restartTimer(View v) {
        tvSend.setClickable(false);
        codeTimer.start();
    }

    private CountDownTimer codeTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tvSend.setText((millisUntilFinished / 1000) + "s");
        }

        @Override
        public void onFinish() {
            try {
                tvSend.setText(getResources().getString(R.string.register_send));
                tvSend.setClickable(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


}
